package com.encryption.logic;

import java.util.HashMap;
import java.util.Map;

public class UserLoginLock {
	private static Map<String, Integer> userIdTimeMap = new HashMap<String, Integer>();
	private static Map<String, Long> userIdLockDateMap = new HashMap<String, Long>();
	private static final int LOCK_ERROR_TIME = 5; 
	private static final int LOCK_DURATION_TIME = 15 * 60 * 60 * 1000; 
	
	public static void addErrorTime(String ipAddr){
		if(userIdTimeMap.containsKey(ipAddr)){
			int time = userIdTimeMap.get(ipAddr);
			if(time >= LOCK_ERROR_TIME){
				userIdLockDateMap.put(ipAddr, System.currentTimeMillis());
			}else{
				time++;
			}
			userIdTimeMap.put(ipAddr, time);
		}else{
			userIdTimeMap.put(ipAddr, 1);
		}
	}
	
	public static boolean isLocked(String ipAddr){
		if(!userIdTimeMap.containsKey(ipAddr))
			return false;
		
		int time = userIdTimeMap.get(ipAddr);
		if(time != -1 && time < LOCK_ERROR_TIME)
			return false;
		
		long curTime = System.currentTimeMillis();
		long lockedTime = userIdLockDateMap.get(ipAddr);
		if(curTime - lockedTime < LOCK_DURATION_TIME)
			return true;
		
		return false;
	}
	
	public static int getErrorTime(String ipAddr){
		return userIdTimeMap.containsKey(ipAddr) ? userIdTimeMap.get(ipAddr) : 1;
	}
	
	public static int getLostErrorTime(String ipAddr){
		int errorTime = getErrorTime(ipAddr);
		return LOCK_ERROR_TIME - errorTime;
	}
	
	public static void unLock(String ipAddr){
		if(userIdTimeMap.containsKey(ipAddr))
			userIdTimeMap.remove(ipAddr);
	}
	
}
